package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.gateway.config.AuthProperties;
import com.leyou.gateway.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        List<String> allowPaths = authProperties.getAllowPaths();

        String uri = request.getPath().toString();
        for (String allowPath : allowPaths) {   //uri   /api/user/check/12345/1   allowPath: /api/user/check
            if(uri.startsWith(allowPath)){
                return chain.filter(exchange);
            }
        }
        String token =  request.getCookies().getFirst( jwtProperties.getUser().getCookieName()).getValue();
        // String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
//        第二步：解密token
        try {
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Long useId = userInfo.getId();
            ServerWebExchange.Builder mutate = exchange.mutate();


            mutate
                    .request(builder -> builder.header("USER_ID",useId.toString()))
                    .build();
            // 6.放行
            return chain.filter(exchange);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
